package com.eastfair.certificate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.projectcore.FormFieldCacheKeyBuilder;
import com.eastfair.certificate.contant.ConfigContant;
import com.eastfair.certificate.dao.FormFieldMapper;
import com.eastfair.certificate.entity.FormField;
import com.eastfair.certificate.entity.FormFieldGroup;
import com.eastfair.certificate.service.FormFieldService;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.certificate.service.FormFieldSubsystemService;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.code.ExceptionCode;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.utils.ClassObjectUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;

/**
 * <p>
 * 业务实现类
 * 动态表单
 * </p>
 *
 * @author ligang
 * @date 2023-05-17
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class FormFieldServiceImpl extends SuperCacheServiceImpl<FormFieldMapper, FormField> implements FormFieldService {

    @Autowired
    FormFieldSubsystemService formFieldSubsystemService;
    @Autowired
    SnowFlakeRole snowFlakeRole;
    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<FormField> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(FormField model) {
        //雪花ID,不需要分库分表
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setIsDeleted(BusinessConstant.NO);
        model.setIsEnabled(BusinessConstant.NO);
        return R.successDef();
    }


    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<FormField> list(FormFieldDTO modelDTO, List<Long> ids) {
        return ((FormFieldService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'languageType', #args[0]?.languageType}," +
                            "{'fieldName', #args[0]?.fieldName}," +
                            "{'fieldEnName', #args[0]?.fieldEnName}," +
                            "{'keyword', #args[0]?.keyword}," +
                            "{'fieldType', #args[0]?.fieldType}," +
                            "{'groupId', #args[0]?.groupId}," +
                            "{'fieldTypeAttribute', #args[0]?.fieldTypeAttribute}," +
                            "{'methodType', #args[0]?.methodType}," +
                            "{'fieldTypeUrlValue', #args[0]?.fieldTypeUrlValue}," +
                            "{'fieldTypeAttributeValue', #args[0]?.fieldTypeAttributeValue}," +
                            "{'placeholder', #args[0]?.placeholder}," +
                            "{'enPlaceholder', #args[0]?.enPlaceholder}," +
                            "{'fieldDesc', #args[0]?.fieldDesc}," +
                            "{'fieldEnDesc', #args[0]?.fieldEnDesc}," +
                            "{'inputLength', #args[0]?.inputLength}," +
                            "{'inputWidth', #args[0]?.inputWidth}," +
                            "{'sequence', #args[0]?.sequence}," +
                            "{'legend', #args[0]?.legend}," +
                            "{'legendDesc', #args[0]?.legendDesc}," +
                            "{'legendEnDesc', #args[0]?.legendEnDesc}," +
                            "{'isEdit', #args[0]?.isEdit}," +
                            "{'isRequired', #args[0]?.isRequired}," +
                            "{'isMultiple', #args[0]?.isMultiple}," +
                            "{'isVerification', #args[0]?.isVerification}," +
                            "{'verificationKeyword', #args[0]?.verificationKeyword}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'labelKey', #args[0]?.labelKey}," +
                            "{'labelValueKey', #args[0]?.labelValueKey}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<FormField> listOfCache(FormFieldDTO modelDTO, List<Long> ids) {
        //查询
        FormField queryModel = new FormField();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }
        QueryWrap<FormField> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(FormField::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(FormField::getIsDeleted, BusinessConstant.DELETE_NO);
        List<FormField> modelList = list(wrapper);
        return modelList;
    }

    @Override
    public R initFormField(FormFieldGroup formFieldGroup) {
        List<String> fieldNameList = new ArrayList<>();
        String dtoClassName = formFieldGroup.getFormClassName();
        try {
            List list = ClassObjectUtil.getFiledsInfo("", new ArrayList(), Class.forName(dtoClassName).newInstance());
            if (list != null && !list.isEmpty()) {
                for (Object object : list) {
                    Map map = (Map) object;
                    fieldNameList.add(map.get("name").toString());
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        for (String fieldName : fieldNameList) {
            FormFieldDTO formFieldDTO = new FormFieldDTO();
            formFieldDTO.setKeyword(fieldName);
            formFieldDTO.setGroupId(formFieldGroup.getId());
            List<FormField> formFieldList = list(formFieldDTO, null);
            if (formFieldList == null || formFieldList.isEmpty()) {
                FormField formField = new FormField();
                formField.setKeyword(fieldName);
                formField.setGroupId(formFieldGroup.getId());
                save(formField);
            }
        }
        return R.success();
    }

    @Override
    public R<String> checkFormFieldInfo(List<FormFieldVO> formFieldVOList) {
        StringBuilder stringBuilder = new StringBuilder();
        // 实体/类名为空 校验失败
        if (Objects.isNull(formFieldVOList) || CollectionUtil.isEmpty(formFieldVOList)) {
            return R.fail(ExceptionCode.ERROR_NULL_PARAMS);
        }
        // 表单校验
//        for (FormFieldVO formFieldVO : formFieldVOList) {
//            String valueStr = (String) formFieldVO.getValue();
//            if (BusinessConstant.YES == formFieldVO.getIsRequired()) {
//                if (StringUtils.isBlank(valueStr)) {
//                    stringBuilder.append(String.format("%s不能为空", formFieldVO.getFieldName()));
//                }
//            }
//            if (!Objects.isNull(formFieldVO.getInputLength())) {
//                if (formFieldVO.getInputLength() < valueStr.length()) {
//                    stringBuilder.append(String.format("%s 长度高于 %s", formFieldVO.getFieldName(), formFieldVO.getInputLength()));
//                }
//            }
//        }
        return R.success(stringBuilder.toString());
    }

    /**
     * 从模板展会拷贝配置到当前展会
     *
     * @param formFieldDTO 配置类型
     */
    private void copyFormTemplate(FormFieldDTO formFieldDTO) {
        QueryWrapper<FormField> temWrapper = new QueryWrapper<>();
        temWrapper.lambda().eq(FormField::getGroupId, formFieldDTO.getGroupId())
                .orderByAsc(FormField::getSequence);
        List<FormField> temList = list(temWrapper);
        temList.forEach(formField -> {
            formField.setGroupId(formFieldDTO.getGroupId());
            formField.setId(snowFlakeRole.findUidSimple());
            formField.setCreateTime(null);
            formField.setUpdateTime(null);
        });
        saveBatch(temList);
    }


    @Override
    public R<Boolean> updateFormField(FormFieldDTO formFieldDTO) {
        if (Objects.isNull(formFieldDTO.getId())) {
            return R.fail(ExceptionCode.ERROR_NULL_ID);
        }
        FormField formField = getByIdCache(formFieldDTO.getId());
        if (Objects.isNull(formField)) {
            return R.fail(ExceptionCode.ERROR_NULL_ID);
        }
        FormField field = BeanUtil.copyProperties(formFieldDTO, FormField.class);
        updateById(field);
        //重新排序
        updateSequece(field, field.getSequence());
        return R.success();
    }

    @Override
    public R updateSequece(FormField formField, int sequence) {
        QueryWrapper<FormField> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FormField::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(formField.getGroupId() != null, FormField::getGroupId, formField.getGroupId())
                .ne(formField.getId() != null, FormField::getId, formField.getId())
                .ge(FormField::getSequence, sequence)
//                .eq(formField.getIsEnabled() != null, FormField::getIsEnabled, formField.getIsEnabled())
        ;
        queryWrapper.orderByAsc("sequence");
        List<FormField> formFieldList = list(queryWrapper);
        if (formFieldList != null && !formFieldList.isEmpty()) {
            for (FormField field : formFieldList) {
                field.setSequence(++sequence);
//                updateById(field);
            }
            updateBatchById(formFieldList);
        }
        return R.success();
    }

    private R<String> getValueStr(String keyword, Object obj, Class<?> clazz) {
        String value = "";
        String methodKey = com.eastfair.core.utils.StringUtils.capitalize(keyword);
        Method method = null;
        try {
            method = clazz.getDeclaredMethod(ConfigContant.METHOD_GET + methodKey, null);
        } catch (NoSuchMethodException e) {
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
        Object object = null;
        try {
            object = method.invoke(JSON.parseObject(JSON.toJSONString(obj), clazz));
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
        if (Objects.isNull(object)) {
            object = "";
        }
        return R.success(object.toString());
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public FormFieldVO doToVo(FormField model) {
        FormFieldVO modelVo = new FormFieldVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<FormFieldVO> doToVos(List<FormField> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<FormFieldVO> result = new ArrayList<>();
        for (FormField model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new FormFieldCacheKeyBuilder();
    }
}
